package org.wxd.email.engine;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.wxd.email.api.EmailService;
import org.wxd.email.api.dto.SendMailRequest;
import org.wxd.email.api.exception.EmailSendException;

import javax.mail.internet.MimeMessage;

/**
 * Created by wangxd on 2015/11/4.
 */
public class EmailServiceImpl implements EmailService {

    private JavaMailSender javaMailSender;
    private String systemEmail;

    public void sendMail(SendMailRequest request) {
        try{
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg);

            mimeMessageHelper.setFrom(systemEmail);
            mimeMessageHelper.setTo(request.to());
            mimeMessageHelper.setSubject(request.subject());
            mimeMessageHelper.setText(request.content());
            javaMailSender.send(msg);
        }catch (Exception e){
            e.printStackTrace();
            throw new EmailSendException("faild to send email.",e);
        }

    }

    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void setSystemEmail(String systemEmail) {
        this.systemEmail = systemEmail;
    }
}
